<?php
/**
 * （Logic）
 */
namespace App\Logic\Amazon\Parse;

use App\Models\Amazon\FBAInventory;
use App\Models\Basics\SysCountry;
use App\Util\RExcel;
class ParseInventoryReport
{
    /**
     * 解析FBAInventory
     * @param $file
     * @param $account
     * @return int
     */
    public static function exeParse($file,$account){
        FBAInventory::query()->where('account_id',$account->id)->delete();
        $lines = RExcel::importFile($file);
        $i = 0;
        $count = 0;
        $head = [];
        foreach($lines as $_str){
            $str = ParseReport::getReplaceStr($_str);
            if($i == 0){
                $head = ParseReport::getTableHeadKey($str,self::$_keys);
                if(empty($head))return 2;
            }else{
                $flag = self::_addFbaInventory($account->id,$head,$str);
                $flag && $count++;
            }
            $i++;
        }
        return $i==($count+1) ? 2 : 3;
    }

    private static $_keys = ['seller-sku', 'asin', 'country', 'quantity-for-local-fulfillment'];

    /**
     * 添加FBAInventory
     * @param $accountId
     * @param $head
     * @param $str
     * @return bool
     */
    private static function _addFbaInventory($accountId,$head,$str){
        if(empty($head))return true;
        if(!$str)return true;
        $temp = explode("\t",$str);
        $keys = self::$_keys;
        $flag = false;
        foreach($keys as $key){
            if(!isset($temp[$head[$key]])){
                $flag = true;
                break;
            }
        }
        if($flag)return true;
        if(!$temp[$head['seller-sku']])return true;
        $country = strtoupper($temp[$head['country']]);
        if('GB' == $country){
            $country = 'UK';
        }
        $countryId = SysCountry::getIdByCountry($country);
        if(!$countryId)return true;
        $re = FBAInventory::query()->updateOrCreate([
            'country_id' => $countryId,
            'seller_sku' =>  $temp[$head['seller-sku']],
        ],[
            'account_id' => $accountId,
            'asin' => $temp[$head['asin']],
            'quantity' => $temp[$head['quantity-for-local-fulfillment']],
        ]);
        return !$re ? false : true;
    }
}
